<template>
  <div class="menu-wrapper">
    <el-form ref="couponForm" :model="form" label-width="100px">
      <el-form-item label="名称" prop="name" :rules="{ required: true, message: '请输入名称', trigger: 'blur' }">
        <el-col :span="6">
          <el-input  placeholder="例:满100减30" v-model="form.name"/>
        </el-col>
      </el-form-item>
      <el-form-item label="使用说明">
        <el-col :span="12">
          <el-input v-model="form.introduction"/>
        </el-col>
      </el-form-item>
      <el-row>
        <el-col :span="5">
          <el-form-item label="券类型" prop="targetType">
            <el-select style="width: 100%" v-model="form.targetType" placeholder="请选择券类型" >
              <el-option label="通用券" :value="Number(0)"/>
              <!-- <el-option label="品牌券" :value="Number(1)"/> -->
              <!-- <el-option label="会员券" :value="Number(2)"/> -->
              <el-option label="分类券" :value="Number(3)"/>
              <!-- <el-option label="商品券" :value="Number(4)"/> -->
               <!-- <el-option label="兑换券" :value="Number(5)"/> -->
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5">
          <el-form-item label="适用场景" prop="scope">
            <el-select style="width: 100%" v-model="form.scope" placeholder="请选择">
              <el-option label="全场" value="0"/> -->
              <!-- <el-option label="店内" value="1"/>
              <el-option label="商城" value="2"/> -->
            <!-- </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-tabs>
        <!--tab1-->
        <el-tab-pane label="优惠信息">
          <el-row>
            <el-col :span="12" v-if="form.targetType===4">
              <el-form-item label="指定产品">
                <el-col :span="12">
                  <el-select ref="productSelect" style="width:100%"  multiple v-model="products" value-key="id"  @focus="dialogShow()">
                    <el-option
                      v-for="item in productAllOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12"  v-if="form.targetType===2">
              <el-form-item label="指定会员等级">
                <el-col :span="12">
                  <el-select style="width:100%" v-model="vips"  value-key="id"  multiple placeholder="请选择">
                    <el-option
                      v-for="item in vipOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.targetType===1">
              <el-form-item label="指定品牌">
                <el-col :span="12">
                  <!--可搜索带选择框-->
                  <el-select style="width:100%"
                             v-model="brands"
                             filterable
                             remote
                             multiple
                             value-key="id"
                             reserve-keyword
                             placeholder="请输入品牌关键字"
                             :filter-method="searchBrand"
                             >
                    <el-option
                      v-for="(item,index) in barrelOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.targetType===3">
              <el-form-item label="指定分类">
                <el-col :span="12">
                  <el-select style="width:100%" v-model="productCategorys" value-key="id"  filterable :filter-method="searchCategorys" multiple placeholder="请选择分类">
                    <el-option
                      v-for="item in productCategorysOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" v-if="form.targetType!=5">
            <el-form-item label="优惠类型" prop="type" :rules="{ required: true, message: '请选择优惠类型', trigger: 'blur' }">
                <el-select style="width: 100%" v-model="form.type" placeholder="请选择" @change="typeChange">
                  <el-option label="满减" value="0"/>
                  <el-option label="满折" value="1"/>
                </el-select>
            </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5" v-if="form.targetType!=5">
              <el-form-item label="使用门槛" prop="minimumPrice"
                            :rules="{ required: true, message: '请输入使用门槛', trigger: 'blur' }">
                <el-input placeholder="消费满多少元可用" v-model="form.minimumPrice"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12"  v-if="form.targetType==5">
              <el-form-item label="补运费">
                <el-col :span="12">
                  <el-input v-model="form.amount"/>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.targetType!=5&&form.type!=2" :label="form.type=='0'?'优惠现金':'优惠折扣(%)'" prop="amount" :rules="{ required: true, message: form.type =='0'?'请输入优惠现金':'请输入优惠折扣(如:95)', trigger: 'blur' }"
                           >
                  <el-input v-model="form.amount"/>
              </el-form-item>
            </el-col>

              <el-form-item label="赠品" prop="productId" :rules="{ required: true, message: '请选择可赠送产品', trigger: 'blur' }"
                            v-if="form.type==2">
                <!--可搜索带选择框-->
                <el-select style="width:100%"
                           v-model="form.productId"
                           filterable
                           remote
                           placeholder="请输入商品关键字"
                           :filter-method="searchProduct"
                           :loading="productLoading">
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="可兑换产品" prop="productId" :rules="{ required: true, message: '请选择可兑换产品', trigger: 'blur' }"
                            v-if="form.targetType==5">
                <!--可搜索带选择框-->
                <el-select style="width:100%"
                           v-model="form.productId"
                           filterable
                           remote
                           placeholder="请输入商品关键字"
                           :filter-method="searchProduct"
                           :loading="productLoading">
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12" v-if="form.type==2||form.targetType==5">
              <el-form-item label="数量" prop="quantity" :rules="{ required: true, message: '请输入数量', trigger: 'blur' }">
                <el-col :span="12">
                  <el-input v-model="form.quantity"/>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="投放">
          <el-row>
            <el-col :span="12">
              <el-form-item label="投放方式" prop="mode" :rules="{ required: true, message: '请选择投放方式', trigger: 'blur' }">
                <el-col :span="7">
                  <el-select style="width: 100%" v-model="form.mode" placeholder="请选择">
                    <el-option label="自由领取" value="0"/>
                    <el-option label="活动投放" value="1"/>
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="form.mode==0">
              <el-form-item label="起始日期">
                <el-col :span="12">
                  <el-date-picker
                    v-model="dateTime"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
          <el-col :span="12">
            <el-form-item label="发行张数" prop="stock" :rules="{ required: true, message: '请输入发行张数', trigger: 'blur' }">
              <el-col :span="7">
                <el-input v-model="form.stock"/>
              </el-col>
            </el-form-item>
          </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" v-if="form.mode==0||form.targetType==5">
<!--              <el-form-item :label="form.targetType==0||form.targetType==5?'月限用量':'每人限领'" prop="maxgiven" :rules="{ required: true, message: '请输入每人限领', trigger: 'blur' }">-->
                <el-form-item label="限领数量" prop="maxgiven" :rules="{ required: true, message: '请输入每人限领', trigger: 'blur' }">
                <el-col :span="7">
                  <el-input placeholder="0表示不限张数" v-model="form.maxgiven"/>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-col :span="12">
          <el-button type="primary" :loading="clicked" @click="saveCoupon('couponForm')">
            &nbsp&nbsp&nbsp&nbsp完 成&nbsp&nbsp&nbsp&nbsp
          </el-button>
        </el-col>
      </el-form-item>
    </el-form>
    <el-dialog
      title="商品选择"
      :visible.sync="orderVisible"
      width="950px"
      style="z-index: 9999"
      v-el-drag-dialog
      :before-close="orderClose">
      <div style="position: relative;z-index:9999">
        <productTable ref="productList" @doubleClick="doubleClick" @orderClose="orderClose"  @addClick="addClick"></productTable>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  .menu-wrapper {
    margin: 15px;
  }
  .dialog-button-slot{
    width: 100%;
    padding-top: 20px;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
</style>
<script>
  import productTable from '../../components/ProductList/productList'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import {EventBus} from '@/api/eventBus'
  import utils from '../../utils/utils.js'
  import {find,update} from '@/api/coupon'
  import {list as brandList} from '@/api/brand'
  import {list as productList} from '@/api/product'
  import {list as productCategoryList} from '@/api/productCategory'
  import {list as memberList} from '@/api/member'
  export default {
    name: 'coupon-edit',
    directives: { elDragDialog },
    filters: {},
    components: {productTable},
    data() {
      return {
        productCategorysOptions:[{
          id: 0,
          name: '菜品'
        }, {
          id: 1,
          name: '套餐'
        },],
        clicked: false, // 按钮防双击
        orderVisible:false,
        form: {
          id: '',
          name: '',
          amount:0,
          beginDate: '',
          endDate: '',
          introduction: '',
          productId: '',
          maxgiven: 1,
          minimumPrice: '',
          targetType:'',
          targets:[],
          mode: '',
          quantity: 1,
          scope: '0',
          stock: 0,
          subType: 0,
          type: '0',
        },
        brands:[],
        members: [],
        productCategorys: [],
        vips: [],
        typeList:[],
        products: [],
        isProduct: false,
        productLoading: false,
        productOptions: [],
        brandLoading: false,
        barrelOptions: [],
        vipOptions: [{id: 0, name: 'vip1'}, {id: 1, name: 'vip2'}, {id: 2, name: 'vip3'}, {id: 3, name: 'vip4'}, {id: 4, name: 'vip5'}],
        memberLoading:false,
        memberOptions:[],
        // productCategorysOptions:[],
        typeId:'0',
        dateTime:[],
        productAllOptions: [],
      }
    },
    created() {
      // this.loadProductCategory('')
      this.loadProduct('')
      this.loadBrand('')
      this.loadMember('')
      this.getData()
    },
    watch:{ // 路由地址不变的情况下,如果id变化则重新获取数据
      $route (newVal, oldVal) {
          console.log(newVal);
        if (newVal.name=='coupon-edit' && newVal.query.id!=this.id) {
          this.getData()
        }
      }
    },
    methods: {
      orderClose() {
        this.orderVisible = false;
      },
      addClick(data){
        var _this = this
        data.forEach(item=>{
          var goodsDetails = {
            id: item.goodsId,
            name: item.name,
            tabId:'1',
          };
          _this.products.push(goodsDetails)
        });
      },
      doubleClick(val) {
        var goodsDetails = {
          id: val.goodsId,
          name: val.name,
          tabId:'1',
        };
        this.products.push(goodsDetails)
      },
      searchCategorys(query){
        this.loadProductCategory(query)

        },
      getData () {
        this.form.id = this.$route.query.id;
        this.products=[]
        find(this.form.id).then(response => {
          this.form=response.data.coupon
          this.dateTime.push(this.form.beginDate);
          this.dateTime.push(this.form.endDate);
          this.form.scope=JSON.stringify(this.form.scope)
          this.form.type=JSON.stringify(this.form.type)
          this.form.mode=JSON.stringify(this.form.mode)
          this.typeList = []
          this.form.targets.forEach(item=>{
            let couponTarget={
              id:item.targetId,
              name:item.targetName,
              tabId:item.productType
            }
            this.typeList.push(couponTarget)
          })
          if (this.form.targetType===1){
            this.brands=this.typeList
            console.log( this.brands)
          }else if (this.form.targetType===2){
            this.vips=this.typeList
          }else if (this.form.targetType===3){
            this.productCategorys=this.typeList
          }else if(this.form.targetType===4){
            this.productAllOptions=this.typeList
            this.products=this.productAllOptions
          }
        }).catch(error => {
        })
      },
      dialogShow() {
        this.orderVisible=true
      },
      typeChange(id) {
        this.typeId = id;
        if (id === '2' || id === '3') {
          this.isProduct = true
        } else {
          this.isProduct = false
        }
      },

      loadProduct(query) {
        let params = new URLSearchParams();
        params.append('pageNum', 1);
        params.append('pageSize', 50);
        params.append('name', query);
        this.productLoading = true;
        productList(params).then(response => {
          this.productLoading = false;
          this.productOptions = response.data.data;
        }).catch(error => {
          this.productLoading = false;
        });
      },
      searchProduct(query) {
        this.loadProduct(query)
      },
      loadBrand(query) {
        let params = new URLSearchParams();
        params.append('pageNum', 1);
        params.append('pageSize', 5000);
        params.append('name', query);
        this.brandLoading = true;
        brandList(params).then(response => {
          console.log(response)
          this.brandLoading = false;
          this.barrelOptions = response.data.data;
        }).catch(error => {
          this.brandLoading = false;
        });
      },
      searchBrand(query) {

        this.loadBrand(query)
      },
      loadMember(query) {
        let params = new URLSearchParams();
        params.append('pageNum', 1);
        params.append('pageSize', 50);
        params.append('name', query);
        this.memberLoading = true;
        memberList(params).then(response => {
          console.log(response)
          this.memberLoading = false;
          this.memberOptions = response.data.data;
        }).catch(error => {
          this.memberLoading = false;
        });
      },
      searchMember(query) {
        this.loadMember(query)
      },
      // loadProductCategory(query) {
      //   let params = new URLSearchParams();
      //   params.append('name',query)
      //   params.append('pageNumber',1)
      //   params.append('pageSize',50)
      //   productCategoryList(params).then(response => {
      //     this.productCategorysOptions=response.data
      //   }).catch(error => {
      //   });
      // },
      saveCoupon(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          if (valid) { // 校验表单
            _this.clicked = true
            this.form.targets=[];
            this.form.status = 0
            if(this.dateTime.length >0){
              this.form.beginDate = this.dateTime[0];
              this.form.endDate = this.dateTime[1]
            }
            if(this.isProduct){
              this.form.amount = 0;
            }
            if (this.brands.length>0){
              this.brands.forEach((item)=>{
                let couponTarget={
                  productType:0,
                  targetId:item.id,
                  targetName:item.name,
                }
                this.form.targets.push(couponTarget)
              })
            }
            if (this.productCategorys.length>0){
              this.productCategorys.forEach((item)=>{
                let couponTarget={
                  productType:0,
                  targetId:item.id,
                  targetName:item.name,
                }
                this.form.targets.push(couponTarget)
              })
            }

            if (this.products.length>0){
              console.log(this.products)
              this.products.forEach((item)=>{
                let couponTarget={
                  productType:item.tabId,
                  targetId:item.id,
                  targetName:item.name,
                }
                this.form.targets.push(couponTarget)
              })

            }
            if (this.vips.length>0){
              this.vips.forEach(item=>{
                let couponTarget={
                  productType:0,
                  targetId:item,
                  targetName:'',
                }
                if (item==0){
                  couponTarget.targetName='vip1'
                }else if (item==1){
                  couponTarget.targetName='vip2'
                }else if (item==2){
                  couponTarget.targetName='vip3'
                }else if (item==3){
                  couponTarget.targetName='vip4'
                } else if (item==4){
                  couponTarget.targetName='vip5'
                }
                this.form.targets.push(couponTarget)
              })
            }
            if (this.form.targetType==5){
              this.form.type=3;
              this.form.mode=1;
            }
            this.form.status=0;
            update(_this.form).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('coupon-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/coupon/list'
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false

            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>
